import React from 'react';
import {Spin, Card, Button, Row, Col, Form, Popconfirm} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, FIXED_COLUMN_WIDTH} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import styles from './style.css';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import {newOrUpdateValidator} from './validator';
import {getDetail} from './api';
import {isYorN} from '../Enum';
const FormItem = Form.Item;
const isYorNList = isYorN.toList(language);
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: [],
        showFile: false,
        errorDetails: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: Object.assign({}, res.data, {
                                // eslint-disable-next-line no-nested-ternary
                                isSecondClaim: (res.data.isSecondClaim === undefined || res.data.isSecondClaim === null) ? undefined : (res.data.isSecondClaim ? 1 : 2),
                                // eslint-disable-next-line no-nested-ternary
                                isInsideShare: (res.data.isInsideShare === undefined || res.data.isInsideShare === null) ? undefined : (res.data.isInsideShare ? 1 : 2)
                            }),
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = newOrUpdateValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const productCategoryId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.productCategoryId !== productCategoryId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, loading} = this.state;
        const {initEnum} = this.props;
        const validateBrandId = !data.brandId && this.state.validate ? 'error' : null;
        const validateCode = !data.code && this.state.validate ? 'error' : null;
        const validateEnterpriseCode = !data.enterpriseCode && this.state.validate ? 'error' : null;
        const validateName = !data.name && this.state.validate ? 'error' : null;
        const validateRemark = data.remark && data.remark.length > 100 && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        if(this.props.initEnum.brands.length === 1 && !this.props.id)
            data.brandId = this.props.initEnum.brands[0].value;
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '订单基本信息'
                    })}>
                        <Form>
                            <Row>
                                {
                                    this.props.initEnum.brands.length !== 1 &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.operation.brandId',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={validateBrandId}
                                            required>
                                            <WrappedSelect
                                                name="brandId"
                                                options={initEnum.brands}
                                                value={data.brandId}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '责任单位编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateCode}
                                    required>
                                        <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.name',
                                        defaultMessage: '责任单位名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateName}
                                    required>
                                        <TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.enterpriseCode',
                                        defaultMessage: '公司代码'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateEnterpriseCode}
                                    required>
                                        <TextInput
                                            name="enterpriseCode"
                                            value={data.enterpriseCode}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.isSecondClaim',
                                            defaultMessage: '是否生成二次索赔'
                                        })}
                                        {...FORM_OPTIONS.item} >
                                        <WrappedSelect
                                            allowClear
                                            name="isSecondClaim"
                                            value={data.isSecondClaim}
                                            options={isYorNList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.isInsideShare',
                                            defaultMessage: '是否生成内部分摊'
                                        })}
                                        {...FORM_OPTIONS.item} >
                                        <WrappedSelect
                                            allowClear
                                            name="isInsideShare"
                                            value={data.isInsideShare}
                                            options={isYorNList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem {...FORM_ROW_OPTIONS.item} label={formatMessage({
                                    id: 'newPanel.operation.remark',
                                    defaultMessage: '备注'
                                })} validateStatus={validateRemark}>
                                    <TextInput
                                        type="textarea"
                                        name="remark"
                                        value={data.remark}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Row>
                        </Form>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onNewOrUpdate
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state),
    initEnum: getinitEnumData(state),
    enterprise: getEnterprise(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details, shareRates) => dispatch(onNewOrUpdate(data, details, shareRates)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
